package com.excilys.formation.projet.ebanking.webapp.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.excilys.formation.projet.ebanking.modele.Role;
import com.excilys.formation.projet.ebanking.modele.Utilisateur;
import com.excilys.formation.projet.ebanking.service.api.IUtilisateurService;

public class CustomUserService implements UserDetailsService {
	
	@Autowired
	IUtilisateurService utilisateurService;
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		Utilisateur utilisateur = utilisateurService.getUtilisateurByLoginFetchRoles(username);
		
		if (utilisateur == null) {
			throw new UsernameNotFoundException(username);
		}
		
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (Role role : utilisateur.getRoles()) {
			authorities.add(new GrantedAuthorityImpl(role.getNom()));
		}
		
		CustomUser customUser = new CustomUser(utilisateur.getId(), utilisateur.getLogin(), utilisateur.getPassword(), true, true, true, true, authorities);
		return customUser;
	}
	
}
